package com.lzf.config;

import com.lzf.handler.CustomAccessDeniedHandler;
import com.lzf.handler.CustomAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Configuration

//开启oauth2,reousrce server模式
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;
    @Value("${security.oauth2.resource.id}")
    private String resourceId;
    @Value("${security.oauth2.client.scope}")
    private String scope;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        CustomAuthenticationEntryPoint customOAuthEntryPoint = new CustomAuthenticationEntryPoint();
        resources
                // 自定义oauthEntryPoint
                .authenticationEntryPoint(customOAuthEntryPoint)
                //oauth_client_details表得=》resource_ids字段值（注意此字段是逗号组合值），在下面配置一个资源id即可
                .resourceId(this.resourceId)
                .accessDeniedHandler(customAccessDeniedHandler)
                //.tokenServices() 可以实现获取token信息，顾名思义再资源校验token是否有效。
                //配置要不要把token信息记录在session中,减少落库查询,默认true
                .stateless(false)
        ;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                //项目所需要的授权范围,这个scope对应oauth_client_details表得scope字段
                .antMatchers("/**").access("#oauth2.hasScope('"+this.scope+"')")
                .and()
                //这个貌似是配置要不要把token信息记录在session中
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
